import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { I18NService } from '@core/i18n/i18n.service'
import { NzMessageService } from 'ng-zorro-antd'
import { STPage, STWidthMode, STColumn, STColumnBadge } from '@delon/abc'

import { TradeService } from '../../trade-abstract.service'
import { IBaseInfoColumn } from '@shared/interfaces/baseInfo'
import { DetailBaseClass } from '@shared/classes/DetailBaseClass'
import { ITradeOnlineCharge, ChargePaidStatusMap } from '@shared/interfaces/trade'
import { PageService } from '@shared/services/page.service'
import { copyTextToClipboard } from 'app/utils/helpers'
import { ISearchOption } from '@shared/interfaces/search'
import { AmtFormatPipe } from '@shared/filters/amt-format.pipe'

@Component({
  selector: 'app-trade-charge-detail',
  templateUrl: './charge-detail.component.html',
  styleUrls: ['./charge-detail.component.css', './../../../../shared/styles/table.less'],
})
export class TradeChargeDetailComponent extends DetailBaseClass<ITradeOnlineCharge> implements OnInit {
  @ViewChild('payUrl') payUrlTpl: TemplateRef<void>

  currencyMap = {}

  /* 表格宽度模式 */
  widthMode: STWidthMode = {
    type: 'strict',
    strictBehavior: 'truncate',
  }

  /* 滚动属性 */
  scroll = {
    x: '300px',
  }

  tradeList = []

  page: STPage = {
    front: false,
    show: false,
  }

  procFlagOptions: ISearchOption[] = []

  firstColumns: IBaseInfoColumn[]
  secondColumns: IBaseInfoColumn[]
  thirdColumns: IBaseInfoColumn[]
  otherInfoColumns: IBaseInfoColumn[]

  acquirerColumns: IBaseInfoColumn[]
  groupColumns: IBaseInfoColumn[]
  merchantColumns: IBaseInfoColumn[]
  storeColumns: IBaseInfoColumn[]
  terminalColumns: IBaseInfoColumn[]

  procBadge: STColumnBadge = {
    5: { text: this.trans('TRADE_STATUS.PENDING'), color: 'processing' },
    2: { text: this.trans('TRADE_STATUS.REJECT'), color: 'error' },
    0: { text: this.trans('TRADE_STATUS.RESOLVE'), color: 'success' },
  }

  columns: STColumn[] = [
    {
      title: '订单号',
      i18n: 'TRADE.ORDER_NUM',
      index: 'orderNum',
      className: 'text-center',
    },
    {
      title: '交易时间',
      i18n: 'TRADE.TRANS_TIME',
      index: 'createdAt',
      className: 'text-center',
      type: 'date',
      dateFormat: 'YYYY-MM-DD HH:mm:ss',
    },
    {
      title: '交易场景',
      i18n: 'TRADE.TRANS_SCENE',
      className: 'text-center',
      render: 'transScene',
    },
    {
      title: '交易类型',
      i18n: 'BIZ.ACQUIRER.OTHER.TRADE.TYPE',
      index: 'busicd',
      className: 'text-center',
    },
    {
      title: '交易金额',
      i18n: 'TRADE.TRANS_AMT',
      index: 'amount',
      className: 'text-center',
      render: 'transAmt',
    },
    {
      title: '状态',
      i18n: 'GENERAL.INFO.STATUS',
      index: 'procFlag',
      type: 'badge',
      badge: this.procBadge,
      className: 'text-center',
      render: 'status',
    },
  ]

  constructor(
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    public tradeService: TradeService,
    public pageService: PageService,
    public msg: NzMessageService,
    private amtFormatPipe: AmtFormatPipe,
  ) {
    super(pageService)
  }

  ngOnInit(): void {
    this.initStatusOptions()
    const orderNum = this.route.snapshot.params['id']
    this.loading = true
    this.tradeService.getChargeDetailWithCurrency(orderNum).subscribe(res => {
      this.generateCurrencyMap(res[0])
      this.renderTrade(res[1])
    })
  }

  initStatusOptions(): void {
    for (const key in this.procBadge) {
      const option = { label: this.procBadge[key].text, value: key }
      this.procFlagOptions.push(option)
    }
  }

  generateCurrencyMap(currencies) {
    currencies.forEach(currency => {
      this.currencyMap[currency.code] = currency.decimal
    })
  }

  renderTrade(chargeDetail: ITradeOnlineCharge): void {
    this.initRelatedTrades(chargeDetail)
    this.initFirstColumns()
    this.initSecondColumns()
    this.initThirdColumns()
    this.initOtherInfoColumns()
    this.initAcquirerColumns()
    this.initGroupColumns()
    this.initMerchantColumns()
    this.initStoreColumns()
    this.initColumns()
    this.loading = false
  }

  initRelatedTrades(chargeDetail: ITradeOnlineCharge) {
    this.detailData = chargeDetail
    this.tradeList = chargeDetail.tradesRelated
  }

  initFirstColumns(): void {
    const { amount, currency } = this.detailData
    const amt = parseInt(amount, 10)
    this.firstColumns = [
      {
        span: 8,
        index: 'created',
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        type: 'date',
      },
      {
        span: 8,
        index: 'creator',
        label: 'USER.TITLE.CREATE',
        labelI18n: 'USER.TITLE.CREATE'
      },
      {
        span: 8,
        index: 'amount',
        label: 'TRADE.TRANS_AMT',
        labelI18n: 'TRADE.TRANS_AMT',
        asyncValue: this.amtFormatPipe.transform(amt, currency),
      },
    ]
  }

  initSecondColumns(): void {
    this.secondColumns = [
      {
        span: 8,
        index: 'onlinePayOrderNum',
        label: 'TRADE.ONLINE_CHARGE.ORDER_NUMBER',
        labelI18n: 'TRADE.ONLINE_CHARGE.ORDER_NUMBER',
      },
      {
        span: 8,
        index: 'status',
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        pipe: this.parseStatus.bind(this),
      },
      {
        span: 8,
        index: this.ifPaidStatus(this.detailData.status) ? 'payTime' : 'expired',
        label: this.ifPaidStatus(this.detailData.status) ? '支付时间' : '有效时间',
        labelI18n: this.ifPaidStatus(this.detailData.status) ? 'GENERAL.INFO.PAY_TIME' : 'GENERAL.INFO.EXPIRED',
        type: 'date',
      },
    ]
  }

  initThirdColumns(): void {
    this.thirdColumns = [
      {
        span: 24,
        index: 'payURL',
        label: '支付链接',
        labelI18n: 'GENERAL.INFO.OTHER.PAYMENT_LINK',
        displayTemplate: this.payUrlTpl,
      },
    ]
  }

  initOtherInfoColumns(): void {
    this.otherInfoColumns = [
      {
        span: 12,
        index: 'commodity',
        label: '商品名称',
        labelI18n: 'TRADE.ONLINE_CHARGE.COMMODITY'
      },
      {
        span: 12,
        index: 'remark',
        label: '收款说明',
        labelI18n: 'TRADE.ONLINE_CHARGE.REMARK'
      },
    ]
  }

  parseStatus(status: string): string {
    try {
      return this.trans(ChargePaidStatusMap[status])
    } catch (e) {
      return this.trans('GENERAL.INFO.NONE')
    }
  }

  initColumns(): void {
    this.initValue.call(this, this.firstColumns)
    this.initValue.call(this, this.secondColumns)
    this.initValue.call(this, this.thirdColumns)
    this.initValue.call(this, this.otherInfoColumns)
    this.initValue.call(this, this.acquirerColumns)
    this.initValue.call(this, this.groupColumns)
    this.initValue.call(this, this.merchantColumns)
    this.initValue.call(this, this.storeColumns)
  }

  ifPaidStatus(status: string): boolean {
    return status === 'Paid' ? true : false
  }

  initAcquirerColumns(): void {
    this.acquirerColumns = [
      {
        span: 8,
        index: 'insCode',
        label: 'GENERAL.INSTITUTION.CODE',
        labelI18n: 'GENERAL.INSTITUTION.CODE',
      },
      {
        span: 8,
        index: 'insName',
        label: 'GENERAL.INSTITUTION.NAME',
        labelI18n: 'GENERAL.INSTITUTION.NAME',
      },
      {
        span: 8,
        index: 'insNameEN',
        label: 'GENERAL.INSTITUTION.NAME_EN',
        labelI18n: 'GENERAL.INSTITUTION.NAME_EN',
      },
    ]
  }

  initGroupColumns(): void {
    this.groupColumns = [
      {
        span: 8,
        index: 'agentCode',
        label: 'GENERAL.AGENT.CODE',
        labelI18n: 'GENERAL.AGENT.CODE',
      },
      {
        span: 8,
        index: 'agentName',
        label: 'GENERAL.AGENT.NAME',
        labelI18n: 'GENERAL.AGENT.NAME',
      },
      {
        span: 8,
        index: 'agentNameEN',
        label: 'GENERAL.AGENT.NAME_EN',
        labelI18n: 'GENERAL.AGENT.NAME_EN',
      },
    ]
  }

  initMerchantColumns(): void {
    this.merchantColumns = [
      {
        span: 8,
        index: 'merNum',
        label: 'GENERAL.MERCHANT.NUM',
        labelI18n: 'GENERAL.MERCHANT.NUM',
      },
      {
        span: 8,
        index: 'merName',
        label: 'GENERAL.MERCHANT.NAME',
        labelI18n: 'GENERAL.MERCHANT.NAME',
      },
      {
        span: 8,
        index: 'merNameEN',
        label: 'GENERAL.MERCHANT.NAME_EN',
        labelI18n: 'GENERAL.MERCHANT.NAME_EN',
      },
    ]
  }

  initStoreColumns(): void {
    this.storeColumns = [
      {
        span: 8,
        index: 'storeNum',
        label: 'GENERAL.STORE.NUM',
        labelI18n: 'GENERAL.STORE.NUM',
      },
      {
        span: 8,
        index: 'storeName',
        label: 'GENERAL.STORE.NAME',
        labelI18n: 'GENERAL.STORE.NAME',
      },
      {
        span: 8,
        index: 'storeNameEN',
        label: 'GENERAL.STORE.NAME_EN',
        labelI18n: 'GENERAL.STORE.NAME_EN',
      },
    ]
  }

  copyUrl(payUrl: string): void {
    if (copyTextToClipboard(payUrl)) {
      this.msg.success(this.trans('GENERAL.INFO.OTHER.COPY_URL.SUCCESS'))
    } else {
      this.msg.error(this.trans('GENERAL.INFO.OTHER.COPY_URL.FAILED'))
    }
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
